#!/user/bin/env python3
# encoding: utf-8

import cv2 as cv
import copy
import numpy as np

file = r'D:\data\rice.png'
image = cv.imread(file)
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
#cv.imshow("二值图像", gray)
_, bw = cv.threshold(gray, 0, 0xff, cv.THRESH_OTSU)

seg = copy.deepcopy(bw)
bin, cnts, hier = cv.findContours(seg, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
count = 0
# pre = 0
# num = 0
countArea= []
countLength = []
for i in range(len(cnts), 0, -1):
    c = cnts[i-1]
    area = cv.contourArea(c)
    length = cv.arcLength(c, True)
    if area < 10:
        continue
    count = count + 1
    countArea.append(area)
    countLength.append(length)
    print("blob", i, ":", area)
    x, y, w, h = cv.boundingRect(c)
    cv.rectangle(image, (x, y), (x + w, y + h), (0, 0, 0xff), 1)
    cv.putText(image, str(count), (x, y), cv.FONT_HERSHEY_PLAIN, 0.5, (0, 0xff, 0))

##求米粒面积的数学期望
aver_Area = np.mean(countArea)
aver_Length = np.mean(countLength)

#方差
var_Area = np.var(countArea)
var_Length = np.var(countLength)

#标准差
std_Area = np.std(countArea, ddof=1)
std_Length = np.std(countLength, ddof=1)

# print("米粒总数量：", count)
# cv.imshow("source img", image)
# cv.imshow("threshold img", bw)
# 判断3sigma范围内的米粒数量
area1 = aver_Area - 1.5 * std_Area
area2 = aver_Area + 1.5 * std_Area
length1 = aver_Length - 1.5 * std_Length
length2 = aver_Length + 1.5 * std_Length
# print(length1, length2,aver_Length)

count1 = 0
count2 = 0
for i in countArea:
    if i > area1 and i < area2:
        count1 = count1 + 1

for j in countLength:
    if j > length1 and j < length2:
        count2 = count2 + 1

print("图中米粒面积大于10的米粒数量为%d。米粒的面积期望为：%.2f，方差为：%.2f，标准差为：%.2f。米粒的长度期望为：%.2f，方差为：%.2f，标准差为：%.2f。"%(count,aver_Area,var_Area,std_Area,aver_Length,var_Length,std_Length))
print("面积3sigma范围内的米粒数量：", count1)
print("长度3sigma范围内的米粒数量：", count2)
cv.imshow("input image", image)
cv.imshow("threshold image", bw)

cv.waitKey(0)
cv.destroyAllWindows()
